package io.afu.httprequest;

import io.afu.common.constant.CommonConstant;
import io.afu.common.exception.BaseException;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class Downloader {

    private String UserAgent = CommonConstant.USER_AGENT;

    private String url;

    private String save;

    private Map<String,String> headers;

    public Downloader(){
        addHeader("User-Agent",this.UserAgent);
    }

    public static Downloader getInstance(){
        return new Downloader();
    }

    public static File checkAndMakeParentDir(File file) throws BaseException{
        if (!file.getParentFile().exists()){
            if (!file.getParentFile().mkdirs()){
                throw new BaseException("文件夹无法创建");
            }
        }
        return file;
    }

    /**
     * 添加Header
     * @param key
     * @param value
     * @return
     */
    public Downloader addHeader(String key,String value){
        if (this.headers == null){
            headers = new HashMap<>();
        }
        headers.put(key,value);
        return this;
    }

    public Downloader addCookie(String key,String value){
        if (headers == null){
            headers = new HashMap<>();
        }
        String cookieContent = headers.get("Cookie");
        if (cookieContent == null || cookieContent.equals("")){
            cookieContent = key+"="+value;
        }else {
            cookieContent+= ";"+key+"="+value;
        }
        headers.put("Cookie",cookieContent);
        return this;
    }

    public String getUserAgent() {
        return UserAgent;
    }

    public void setUserAgent(String userAgent) {
        UserAgent = userAgent;
    }

    public String getUrl() {
        return url;
    }

    public Downloader setUrl(String url) {
        this.url = url;
        return this;
    }

    public String getSave() {
        return save;
    }

    public Downloader setSave(String save) {
        this.save = save;
        return this;
    }

    /**
     *
     * @throws BaseException 错误抛出
     */
    public void d() throws BaseException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse response = httpClient.execute(httpGet);
            try {
//                httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
                for (Map.Entry<String,String> entry:headers.entrySet()){
                    httpGet.addHeader(entry.getKey(),entry.getValue());
                }
                HttpEntity entity = response.getEntity();
                long len = entity.getContentLength();
                InputStream inputStream = entity.getContent();
                File file = new File(this.save);
                Downloader.checkAndMakeParentDir(file);
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                int inByte;
                while ((inByte = inputStream.read()) != -1){
                    fileOutputStream.write(inByte);
                }
                inputStream.close();
                fileOutputStream.close();
            }catch (Exception e){
                throw new BaseException(e);
            }
            finally {
                try {
                    response.close();
                }catch (Exception e){
                    throw new BaseException(e);
                }
            }
        }catch (Exception e){
            throw new BaseException(e);
        }
        finally {
            try {
                httpClient.close();
            }catch (Exception e){
                throw new BaseException(e);
            }

        }
    }


    /**
     *
     * @param url 下载路径
     * @param savePath 保存路径
     * @throws BaseException 错误抛出
     */
    public static void d(String url,String savePath) throws BaseException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse response = httpClient.execute(httpGet);
            try {
                httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
                HttpEntity entity = response.getEntity();
                long len = entity.getContentLength();
                InputStream inputStream = entity.getContent();
                File file = new File(savePath);
                Downloader.checkAndMakeParentDir(file);
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                int inByte;
                while ((inByte = inputStream.read()) != -1){
                    fileOutputStream.write(inByte);
                }
                inputStream.close();
                fileOutputStream.close();
            }catch (Exception e){
                throw new BaseException(e);
            }
            finally {
                try {
                    response.close();
                }catch (Exception e){
                    throw new BaseException(e);
                }
            }
        }catch (Exception e){
            throw new BaseException(e);
        }
        finally {
            try {
                httpClient.close();
            }catch (Exception e){
                throw new BaseException(e);
            }

        }
    }



}
